package com.software.levelupandroid.mine.view;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Badge;
import com.software.levelupandroid.entity.Grade;
import com.software.levelupandroid.entity.MergedBadge;
import com.software.levelupandroid.entity.Resource;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.mine.adapter.BadgeAdapter;
import com.software.levelupandroid.mine.viewModel.MineViewModel;
import com.software.levelupandroid.taskShow.TaskShowActivity;
import com.software.levelupandroid.utils.ToastUtil;
import com.software.levelupandroid.utils.UserUtil;
import com.software.levelupandroid.views.NodeProgressBar;
import com.software.levelupandroid.views.ZzHorizontalProgressBar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class MineActivity extends AppCompatActivity {
    private Toolbar toolbarMine;
    private CircleImageView civMineAvatar;
    private TextView tvMineName;
    private TextView tvMineEmail;
    private TextView tvMineNote;
    private NodeProgressBar npbMine;
    private TextView tvMineNowLevel;
    private TextView tvMineGoalLevel;
    private ZzHorizontalProgressBar zhpbMine;
    private TextView tvMineExperience;
    private TextView tvMineMaxExperience;
    private RecyclerView rvBadgeLearn;
    private RecyclerView rvBadgeLife;
    private RecyclerView rvBadgeSport;
    private RecyclerView rvBadgeMind;
    private BadgeAdapter badgeAdapterLearn;
    private BadgeAdapter badgeAdapterLife;
    private BadgeAdapter badgeAdapterSport;
    private BadgeAdapter badgeAdapterMind;
    private LinearLayout tvMineBadge;
    private ImageButton ibMine;
    private LinearLayout llMine;
    private MineViewModel mineViewModel;
    private List<NodeProgressBar.Node> nodeList = new ArrayList<>();
    private boolean isCollapse = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);

        initView();
        initNodeList();

        initViewModel();
        observeLiveData();
        mineViewModel.getAllGrade(MineActivity.this);
        mineViewModel.getAllBadge(MineActivity.this);
        mineViewModel.getBadgeByUserId(MineActivity.this);

        initToolbar();

//        initData();

        initNodeProgressBar();

        setListener();

    }

    @Override
    protected void onResume() {
        initData();
        super.onResume();
    }

    private void setListener() {
        tvMineBadge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isCollapse){
                    isCollapse = false;
                    Drawable expand = ContextCompat.getDrawable(MineActivity.this, R.drawable.baseline_keyboard_arrow_down_24);
                    ibMine.setImageDrawable(expand);
                    llMine.setVisibility(View.VISIBLE);

                    mineViewModel.getMergedBadge(MineActivity.this);
                }else {
                    isCollapse = true;
                    Drawable collapse = ContextCompat.getDrawable(MineActivity.this, R.drawable.baseline_keyboard_arrow_right_black_24);
                    ibMine.setImageDrawable(collapse);
                    llMine.setVisibility(View.INVISIBLE);
                }
            }
        });
    }


    /**
     * 初始化结点列表
     */
    private void initNodeList() {

        NodeProgressBar.Node node0 = new NodeProgressBar.Node();
        node0.topTxt = "Lv0";
        node0.bottomTxt = "0级";
        nodeList.add(node0);

        NodeProgressBar.Node node1 = new NodeProgressBar.Node();
        node1.topTxt = "Lv1";
        node1.bottomTxt = "1级";
        nodeList.add(node1);

        NodeProgressBar.Node node2 = new NodeProgressBar.Node();
        node2.topTxt = "Lv2";
        node2.bottomTxt = "2级";
        nodeList.add(node2);

        NodeProgressBar.Node node3 = new NodeProgressBar.Node();
        node3.topTxt = "Lv3";
        node3.bottomTxt = "3级";
        nodeList.add(node3);

        NodeProgressBar.Node node4 = new NodeProgressBar.Node();
        node4.topTxt = "Lv4";
        node4.bottomTxt = "4级";
        nodeList.add(node4);

        NodeProgressBar.Node node5 = new NodeProgressBar.Node();
        node5.topTxt = "Lv5";
        node5.bottomTxt = "5级";
        nodeList.add(node5);

        NodeProgressBar.Node node6 = new NodeProgressBar.Node();
        node6.topTxt = "Lv6";
        node6.bottomTxt = "6级";
        nodeList.add(node6);

        NodeProgressBar.Node node7 = new NodeProgressBar.Node();
        node7.topTxt = "Lv7";
        node7.bottomTxt = "7级";
        nodeList.add(node7);
    }

    /**
     * 结点进度条显示
     */
    private void initNodeProgressBar() {
        npbMine.setNodeList(nodeList);

        User user = UserUtil.getUser(this);
        int gradeId = user.getGradeId();

        for (int i = 0; i <= gradeId; ++i){
            nodeList.get(i).nodeState = NodeProgressBar.Node.NodeState.REACHED;
            nodeList.get(i).nodeAfterLineState = NodeProgressBar.Node.LineState.REACHED;
        }
        for(int i = gradeId+1; i<nodeList.size(); ++i){
            nodeList.get(i).nodeState = NodeProgressBar.Node.NodeState.UNREACHED;
            nodeList.get(i).nodeAfterLineState = NodeProgressBar.Node.LineState.UNREACHED;
        }

    }

    /**
     * 初始化数据
     */
    private void initData() {
        User user = UserUtil.getUser(this);

        if (user != null){
            //加载头像
            Glide.with(this)
                    .load(user.getAvatar())
                    .into(civMineAvatar);
            //加载用户名称
            tvMineName.setText(user.getUsername());
            //加载用户邮箱
            tvMineEmail.setText(user.getEmail());
            //加载个性签名
            if (user.getSignature() != null){
                tvMineNote.setText(user.getSignature());
            }
            //加载用户等级

            //加载目标等级

            //加载用户经验值

            //加载目标等级所需经验值

            //进度条经验值显示
//            zhpbMine.setMax();
//            zhpbMine.setProgress();

        }

    }

    /**
     * 控件绑定
     */
    private void initView() {
        toolbarMine = findViewById(R.id.toolbar_mine);
        civMineAvatar = findViewById(R.id.civ_mine_avatar);
        tvMineName = findViewById(R.id.tv_mine_name);
        tvMineEmail = findViewById(R.id.tv_mine_email);
        tvMineNote = findViewById(R.id.tv_mine_note);
        npbMine = findViewById(R.id.npb_mine);
        tvMineNowLevel = findViewById(R.id.tv_mine_nowLevel);
        tvMineGoalLevel = findViewById(R.id.tv_mine_goalLevel);
        zhpbMine = findViewById(R.id.zhpb_mine);
        tvMineExperience = findViewById(R.id.tv_mine_experience);
        tvMineMaxExperience = findViewById(R.id.tv_mine_max_experience);
        rvBadgeLearn = findViewById(R.id.rv_badge_learn);
        rvBadgeLife = findViewById(R.id.rv_badge_life);
        rvBadgeSport = findViewById(R.id.rv_badge_sport);
        rvBadgeMind = findViewById(R.id.rv_badge_mind);
        tvMineBadge = findViewById(R.id.tv_mine_badge);
        ibMine = findViewById(R.id.ib_mine);
        llMine = findViewById(R.id.ll_mine);
    }

    /**
     * 初始化ViewModel
     */
    private void initViewModel() {
        ViewModelProvider viewModelProvider = new ViewModelProvider(this);
        mineViewModel = viewModelProvider.get(MineViewModel.class);
    }

    /**
     * 观察等级列表的LiveData
     */
    private void observeLiveData() {
        mineViewModel.getGradeListLiveData().observe(this, new Observer<Resource<List<Grade>>>() {
            @Override
            public void onChanged(Resource<List<Grade>> listResource) {
                if (listResource != null){
                    if (listResource.isSuccess()){
                        List<Grade> gradeList = listResource.getData();
                        User user = UserUtil.getUser(MineActivity.this);
                        int gradeId = user.getGradeId();
                        //加载用户等级
                        if (gradeId > 0)
                            tvMineNowLevel.setText(gradeList.get(gradeId - 1).getTitle());
                        else
                            tvMineNowLevel.setText("Lv0");
                        //加载目标等级
                        tvMineGoalLevel.setText(gradeList.get(gradeId).getTitle());
                        //加载用户经验值
                        tvMineExperience.setText(String.valueOf(user.getExperience()));
                        //加载目标等级所需经验值
                        tvMineMaxExperience.setText(String.valueOf(gradeList.get(gradeId).getExperience()));
                        //进度条经验值显示
                        Double experience = user.getExperience();
                        int progress = (int) Math.round(experience);
                        Double experience1 = gradeList.get(gradeId).getExperience();
                        int max = (int) Math.round(experience1);
                        zhpbMine.setMax(max);
                        zhpbMine.setProgress(progress);

                    }else if (listResource.isFailure()){
                        ToastUtil.showToastOnUI(MineActivity.this, listResource.getErrorMessage());
                    } else if (listResource.isLoading()) {

                    }
                }
            }
        });

        mineViewModel.getBadgeListLiveData().observe(this, new Observer<Resource<List<Badge>>>() {
            @Override
            public void onChanged(Resource<List<Badge>> listResource) {
                if (listResource != null){
                    if (listResource.isSuccess()){
                        List<Badge> data = listResource.getData();
                    }else if (listResource.isFailure()){
                        ToastUtil.showToastOnUI(MineActivity.this, listResource.getErrorMessage());
                    } else if (listResource.isLoading()) {

                    }
                }
            }
        });

        mineViewModel.getOwnBadgeListLiveData().observe(this, new Observer<Resource<List<Badge>>>() {
            @Override
            public void onChanged(Resource<List<Badge>> listResource) {
                if (listResource != null){
                    if (listResource.isSuccess()){
                        List<Badge> data = listResource.getData();
                    }else if (listResource.isFailure()){
                        ToastUtil.showToastOnUI(MineActivity.this, listResource.getErrorMessage());
                    } else if (listResource.isLoading()) {

                    }
                }
            }
        });

        mineViewModel.getMergedBadgeListLiveData().observe(this, new Observer<Resource<MergedBadge>>() {
            @Override
            public void onChanged(Resource<MergedBadge> mergedBadgeResource) {
                if (mergedBadgeResource != null){
                    if (mergedBadgeResource.isSuccess()){
                        MergedBadge data = mergedBadgeResource.getData();

                        List<Badge> badgeList = data.getBadgeList();
                        List<Badge> ownBadgeList = data.getOwnBadgeList();

                        List<Badge> learnBadgeList = new ArrayList<>();
                        List<Badge> lifeBadgeList = new ArrayList<>();
                        List<Badge> sportBadgeList = new ArrayList<>();
                        List<Badge> mindBadgeList = new ArrayList<>();

                        List<Badge> ownLearnBadgeList = new ArrayList<>();
                        List<Badge> ownLifeBadgeList = new ArrayList<>();
                        List<Badge> ownSportBadgeList = new ArrayList<>();
                        List<Badge> ownMindBadgeList = new ArrayList<>();

                        Collections.reverse(ownBadgeList);

                        for (Badge badge : ownBadgeList){
                            switch (badge.getBadgeType()){
                                case 1:
                                    ownLearnBadgeList.add(badge);
                                    break;
                                case 2:
                                    ownLifeBadgeList.add(badge);
                                    break;
                                case 3:
                                    ownSportBadgeList.add(badge);
                                    break;
                                case 4:
                                    ownMindBadgeList.add(badge);
                                    break;
                                default:
                                    break;
                            }
                        }

                        for (Badge badge : badgeList){
                            switch (badge.getBadgeType()){
                                case 1:
                                    learnBadgeList.add(badge);
                                    break;
                                case 2:
                                    lifeBadgeList.add(badge);
                                    break;
                                case 3:
                                    sportBadgeList.add(badge);
                                    break;
                                case 4:
                                    mindBadgeList.add(badge);
                                    break;
                                default:
                                    break;
                            }
                        }

                        rvBadgeLearn.setLayoutManager(new LinearLayoutManager(MineActivity.this, LinearLayoutManager.HORIZONTAL, false));
                        rvBadgeLife.setLayoutManager(new LinearLayoutManager(MineActivity.this, LinearLayoutManager.HORIZONTAL, false));
                        rvBadgeSport.setLayoutManager(new LinearLayoutManager(MineActivity.this, LinearLayoutManager.HORIZONTAL, false));
                        rvBadgeMind.setLayoutManager(new LinearLayoutManager(MineActivity.this, LinearLayoutManager.HORIZONTAL, false));

                        badgeAdapterLearn = new BadgeAdapter(learnBadgeList, ownLearnBadgeList, MineActivity.this);
                        rvBadgeLearn.setAdapter(badgeAdapterLearn);

                        badgeAdapterLife = new BadgeAdapter(lifeBadgeList, ownLifeBadgeList, MineActivity.this);
                        rvBadgeLife.setAdapter(badgeAdapterLife);

                        badgeAdapterSport = new BadgeAdapter(sportBadgeList, ownSportBadgeList, MineActivity.this);
                        rvBadgeSport.setAdapter(badgeAdapterSport);

                        badgeAdapterMind = new BadgeAdapter(mindBadgeList, ownMindBadgeList, MineActivity.this);
                        rvBadgeMind.setAdapter(badgeAdapterMind);

                    }else if (mergedBadgeResource.isFailure()){
                        ToastUtil.showToastOnUI(MineActivity.this, mergedBadgeResource.getErrorMessage());
                    } else if (mergedBadgeResource.isLoading()) {

                    }
                }
            }
        });
    }


    /**
     * 初始化导航栏
     */
    private void initToolbar() {
        setSupportActionBar(toolbarMine);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null){
            actionBar.setDisplayShowTitleEnabled(false);
        }
    }

    /**
     * 初始化菜单栏
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_mine_menu, menu);
        return true;
    }

    /**
     * 菜单item的点击事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.menu_mine_edit:
                Intent intent = new Intent(MineActivity.this, EditUserActivity.class);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 向上按钮的点击监听
     * @return
     */
    @Override
    public boolean onSupportNavigateUp() {
        finish();
        return true;
    }
}